/*
124. 二叉树中的最大路径和
https://leetcode.cn/problems/binary-tree-maximum-path-sum/description/
困难 2024/11/15
*/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
int ans=-1001;
int test(TreeNode* root)
{
    if(root==nullptr) return 0;
    int l=test(root->left);
    int r=test(root->right);
    int val=root->val;
    ans=max(ans,l+r+val);
    return max(max(l,r)+val,0);
}
    int maxPathSum(TreeNode* root) {
        test(root);
        return ans;
    }
};